package com.htjc.integral.account.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.account.mapper.newdb.EcBpAccountIntegralDetailMapper;
import com.htjc.integral.account.mapper.newdb.EcBpAccountIntegralMapper;
import com.htjc.integral.account.mapper.newdb.EcBpConsNoIntegralMapper;
import com.htjc.integral.account.mapper.newdb.EcBpIncomeIntegralMapper;
import com.htjc.integral.account.service.INewAccountService;
import com.htjc.integral.account.service.ISchedulerService;
import com.htjc.integral.account.util.RedisTem;
import com.htjc.integral.account.util.enums.NewAccountConstant;
import com.htjc.integral.common.util.TimeUtil;
import com.htjc.integral.common.util.UUIDUtil;
import com.htjc.integral.model.newaccount.EcBpAccountIntegral;
import com.htjc.integral.model.newaccount.EcBpAccountIntegralDetail;
import com.htjc.integral.model.newaccount.EcBpConsNoIntegral;
import com.htjc.integral.model.newaccount.EcBpInComeIntegral;

import lombok.extern.slf4j.Slf4j;

/**
 * 账户服务所有定时调度任务
 * 
 * @author hlc
 *
 */
@Slf4j(topic = "jfLog")
@Service
@EnableScheduling
public class SchedulerServiceImpl implements ISchedulerService {

	/** 积分账户明细表 */
	@Autowired
	private EcBpAccountIntegralDetailMapper accountIntegralDetailMapper;

	@Autowired
	private INewAccountService accountServiceImpl;

	@Autowired
	private EcBpIncomeIntegralMapper ecBpIncomeIntegralMapper;

	@Autowired
	private EcBpConsNoIntegralMapper ecBpConsNoIntegralMapper;

	@Autowired
	private EcBpAccountIntegralMapper ecBpAccountIntegralMapper;

	@Autowired
	private RedisTem redisTem;

	@Autowired
	private AccountCheckingServiceImpl accountCheckingServiceImpl;

	@Autowired
	private EcBpIncomeIntegralMapper incomeIntegralMapper;

	private  final SimpleDateFormat sdf0 = new SimpleDateFormat("yyyyMMdd");
	private  final SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd");

	/** 调度任务执行的服务器  */
	private static String scheduledIp;

	@Value("${scheduledIp}")
	public void setScheduledIp(String scheduledIp1){
		scheduledIp=scheduledIp1;
	}

	/**
	 * 失败数据同步至资产中心 定时任务，将同步给资产中心失败的数据同步至资产中心
	 */
	@Scheduled(cron = "0 0/5 * * * ?")
	public void syncAssetCentre() {
		String logMsg = "【失败数据同步至资产中心】";
		try {
			if(!InetAddress.getLocalHost().getHostAddress().equals(scheduledIp)){
				return;
			}
		} catch (UnknownHostException e) {
			log.error(logMsg+"获取服务器IP失败");
		}
		log.info(logMsg + "定时任务开始----------------------------->>>");
		// 查询
		List<EcBpAccountIntegralDetail> failDetailList = accountIntegralDetailMapper.selectFailDetail();
		if (failDetailList != null && failDetailList.size() != 0) {
			log.info(logMsg + "共{}条失败数据", failDetailList.size());
			for (int i = 0; i < failDetailList.size(); i++) {
				log.info(logMsg + "第{}条数据处理开始-------->>", i + 1);
				EcBpAccountIntegralDetail accountIntegralDetail = failDetailList.get(i);
				JSONObject json = new JSONObject();
				json.put("ACCOUNT_ID", accountIntegralDetail.getAccountId());
				json.put("ACCOUNT_NAME", accountIntegralDetail.getAccountName());
				json.put("CHANNEL_NO", accountIntegralDetail.getChannelNo());
				json.put("BUSINESS_ID", accountIntegralDetail.getSerialNo());
				json.put("BUSS_TYPE", accountIntegralDetail.getBussType());
				json.put("INTEGRAL", accountIntegralDetail.getBalance());
				json.put("ACCT_DATE", accountIntegralDetail.getAcctDate());
				// 调用资产中心变更积分接口
				JSONObject result = accountServiceImpl.modifyIntegral(json, accountIntegralDetail.getDealType(),
						logMsg);
				accountIntegralDetail.setStatus(result.getString("resultCode"));// 同步至资产中心状态（0:失败1:成功）
				accountIntegralDetailMapper.update(accountIntegralDetail);
				log.info(logMsg + "积分账户明细表更新成功,流水号:" + accountIntegralDetail.getSerialNo() + ",同步状态:"
						+ result.getString("resultCode"));
				log.info(logMsg + "第{}条数据处理完成-------->>", i + 1);
			}
		} else {
			log.info(logMsg + "无失败数据");
		}
		log.info(logMsg + "定时任务结束----------------------------->>>");
	}

	/**
	 * 定时检查过期的收入积分，并修改状态
	 */
	//	@Scheduled(cron = "0 30 11 * * ? ")
	@Transactional
	public void checkStaleIncome() {
		String logMsg = "【过期积分处理】";
		log.info(logMsg + "定时任务开始----------------------------->>>");
		try {
			//查询积分收入表过期积分
			List<EcBpInComeIntegral> incomeIntegralList = ecBpIncomeIntegralMapper.selectStaleIntegral(TimeUtil.getDate("YYYYMMdd"));
			//判断返回结果集非空验证
			if (incomeIntegralList != null && incomeIntegralList.size() > 0) {
				log.info(logMsg + "积分收入表共{}条过期数据", incomeIntegralList.size());
				//根据返回的List去积分修改状态
				ecBpIncomeIntegralMapper.updateToStale(incomeIntegralList);
				log.info(logMsg + "积分收入表更新过期状态成功");
				//根据账户户号分组 修改户号账户表积分
				List<EcBpInComeIntegral> selectStatusList = ecBpIncomeIntegralMapper.selectAccountConsNoStale(TimeUtil.getDate("YYYYMMdd"));
				if (selectStatusList != null && selectStatusList.size() > 0) {
					log.info(logMsg + "账户户号分组共{}条过期积分数据", selectStatusList.size());
					List<EcBpConsNoIntegral> ecBpConsNoList = new ArrayList<>();
					for (EcBpInComeIntegral ecBpInComeIntegral : selectStatusList) {
						EcBpConsNoIntegral ecBpConsNoIntegral = new EcBpConsNoIntegral();
						ecBpConsNoIntegral.setAccountId(ecBpInComeIntegral.getAccountId());
						ecBpConsNoIntegral.setConsNo(ecBpInComeIntegral.getConsNo());
						ecBpConsNoIntegral.setBalance(ecBpInComeIntegral.getUsableBalance());
						ecBpConsNoIntegral.setUpdateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
						ecBpConsNoList.add(ecBpConsNoIntegral);
					}
					ecBpConsNoIntegralMapper.EcBpConsNoIntegralUpdate(ecBpConsNoList);
					log.info(logMsg + "户号账户表可用积分和过期积分更新成功");
				}
				// 积分账户明细表增加 扣减记录
				List<EcBpInComeIntegral> selectEcBpInComeList = ecBpIncomeIntegralMapper.selectAccountStale(TimeUtil.getDate("YYYYMMdd"));
				List<EcBpAccountIntegralDetail> ecBpAccountList = new ArrayList<>();
				for (int i = 0; i < selectEcBpInComeList.size(); i++) {
					EcBpAccountIntegralDetail ecBpAccountIntegralDetail = new EcBpAccountIntegralDetail();
					ecBpAccountIntegralDetail.setDetailId(UUIDUtil.getUUID());
					ecBpAccountIntegralDetail.setAccountId(selectEcBpInComeList.get(i).getAccountId());
					ecBpAccountIntegralDetail.setSerialNo(UUIDUtil.getUUID());
					ecBpAccountIntegralDetail.setDealType(NewAccountConstant.DEAL_TYPE_EXPEND);
					ecBpAccountIntegralDetail.setBalance(selectEcBpInComeList.get(i).getUsableBalance());
					ecBpAccountIntegralDetail.setDealTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
					ecBpAccountIntegralDetail.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
					ecBpAccountIntegralDetail.setBussDiscrible("过期积分");
					ecBpAccountIntegralDetail.setBussType(NewAccountConstant.BUSS_TYPE_GQJFKJ);//13:过期积分扣减
					ecBpAccountIntegralDetail.setAcctDate(TimeUtil.getDate("YYYYMMdd"));
					ecBpAccountIntegralDetail.setChannelNo(NewAccountConstant.CAHNNEL_NO_DEB);
					ecBpAccountList.add(ecBpAccountIntegralDetail);
				}
				accountIntegralDetailMapper.EcBpAccountIntegralDetailInsert(ecBpAccountList);
				log.info(logMsg + "积分账户明细表增加成功");
				// 更新积分账户总表 可用积分 和 过期积分
				List<EcBpAccountIntegral> ecBpAccountIntegralList = new ArrayList<>();
				for (int i = 0; i < selectEcBpInComeList.size(); i++) {
					EcBpAccountIntegral ecBpAccountIntegral = new EcBpAccountIntegral();
					ecBpAccountIntegral.setAccountId(selectEcBpInComeList.get(i).getAccountId());
					ecBpAccountIntegral.setBalance(selectEcBpInComeList.get(i).getUsableBalance());
					ecBpAccountIntegral.setUpdateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
					ecBpAccountIntegralList.add(ecBpAccountIntegral);
				}
				ecBpAccountIntegralMapper.ecBpAccountIntegralUpdate(ecBpAccountIntegralList);
				log.info(logMsg + "积分账户总表可用积分和过期积分更新成功");
				// 调用资产中心接口扣减该账户积分
				for (EcBpAccountIntegralDetail detail : ecBpAccountList) {
					JSONObject json = new JSONObject();
					json.put("BUSINESS_ID", detail.getSerialNo());// 流水号ID
					json.put("ACCOUNT_NAME", detail.getAccountName());// 账号名称
					json.put("CHANNEL_NO", detail.getChannelNo());// 渠道编码
					json.put("ACCOUNT_ID", detail.getAccountId());// 账号ID
					json.put("BUSS_TYPE", detail.getBussType());// 业务类型
					json.put("INTEGRAL", detail.getBalance());// 过期积分
					json.put("ACCT_DATE", detail.getAcctDate());
					JSONObject accountJson = accountServiceImpl.modifyIntegral(json, NewAccountConstant.DEAL_TYPE_EXPEND, logMsg);
					detail.setStatus(accountJson.getString("resultCode"));
					int EcBpAccountUpdate = accountIntegralDetailMapper.update(detail);
					if (EcBpAccountUpdate > 0) {
						log.info(logMsg + "更新成功,流水号:" +detail.getSerialNo() + ",同步状态:"+ accountJson.getString("resultCode"));
					}
				}
			} else {
				log.info(logMsg + "无积分过期数据");
			}
			log.info(logMsg + "定时任务结束----------------------------->>>");

		} catch (Exception e) {
			log.info("错误信息:：   " +e);
			throw new RuntimeException(e.getMessage());
		}

	}

	//@Scheduled(cron = "0 30 11 * * ? ")
	//@Scheduled(cron = "0/5 * * * * ? ")
	@Scheduled(cron = "0 0 3,5,7 * * ?")
	public void task(){
		Map<String, Object> params=new HashMap<String, Object>();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		String datS = sdf0.format(calendar.getTime())  + "000000";
		String datE = sdf0.format(calendar.getTime())  + "235959";
		params.put("starttime", datS);
		params.put("endtime", datE);
		params.put("acctstatus", "0");
		params.put("shortCode", "33101");
		params.put("longCode", "330000");
		log.info("浙江对账开始时间===="+datS);
		List<Map<String, Object>> incomList=incomeIntegralMapper.selectPageDate(params);
		int startsize=incomList.size();
		if(startsize>0) {
			log.info("=====================》浙江对账开始《========================");
			log.info("浙江对账查询出的对账数据数量："+startsize);
			accountCheckingServiceImpl.scoreConverAccDetailNewAll(params,incomList);
			params.put("acctstatus", "1");
			List<Map<String, Object>> incomList1=incomeIntegralMapper.selectPageDate(params);
			log.info("浙江对账成功的数据数量："+incomList1.size());
			log.info("浙江对账数据描述========》推送数据"+startsize+"成功数据"+incomList1.size()+"失败数据"+(startsize-incomList1.size()));
			//	    	accountCheckingServiceImpl.scoreConverAccDetailNewAll(params);
			log.info("=====================》浙江对账结束《========================");
		}else {
			log.info("=====================》浙江对账全部结束《========================");
		}
		
		//do anything
	}

}
